import React, { Component } from 'react';
import PropTypes from "prop-types";

class TodoItem extends Component {
    constructor(props) {
        super(props)
        this.handleClick = this.handleClick.bind(this)
    }
    //父组件传来的props参数发生改变时且被重新render之后被执行
    componentWillReceiveProps() {
        console.log('child componentWillReceiveProps')
    }
    //利用shouldComponentUpdate来提升性能，不然每次父组件渲染子组件也会跟着render
    shouldComponentUpdate(nextProps, nextState) {
        if (nextProps.content !== this.props.content) {
            return true;
        } else {
            return false;
        }
    }
    // 组件被移除之前执行
    componentWillUnmount() {
        console.log('child componentWillUnmount')
    }
    //当组件的state或者props发生改变的时候，render函数就会重新执行
    //当父组件的render运行时，子组件的render函数都将被运行一次
    render() {
        console.log('child render')
        const { content, test } = this.props;
        return (
            <div onClick={this.handleClick}>
                {test} {content}
            </div>
        )
    }
    handleClick() {
        const { itemDelete, index } = this.props
        itemDelete(index)
    }

}
//参数校验
TodoItem.propTypes = {
    test: PropTypes.string.isRequired,
    content: PropTypes.string,
    itemDelete: PropTypes.func,
    index: PropTypes.number
}
//默认属性
TodoItem.defaultProps = {
    test: 'hello world'
}

export default TodoItem;